import { defineStore } from 'pinia'
import { ref } from 'vue'

export const useAppStore = defineStore('app', () => {
  // 状态
  const sidebarCollapsed = ref(false)
  const theme = ref<'light' | 'dark'>('light')
  const loading = ref(false)
  const breadcrumbs = ref<Array<{ title: string; path?: string }>>([])
  
  // 切换侧边栏折叠状态
  const toggleSidebar = () => {
    sidebarCollapsed.value = !sidebarCollapsed.value
    localStorage.setItem('sidebarCollapsed', String(sidebarCollapsed.value))
  }
  
  // 设置主题
  const setTheme = (newTheme: 'light' | 'dark') => {
    theme.value = newTheme
    localStorage.setItem('theme', newTheme)
    
    // 更新HTML类名
    if (newTheme === 'dark') {
      document.documentElement.classList.add('dark')
    } else {
      document.documentElement.classList.remove('dark')
    }
  }
  
  // 设置加载状态
  const setLoading = (status: boolean) => {
    loading.value = status
  }
  
  // 设置面包屑
  const setBreadcrumbs = (newBreadcrumbs: Array<{ title: string; path?: string }>) => {
    breadcrumbs.value = newBreadcrumbs
  }
  
  // 初始化应用状态
  const initialize = () => {
    // 恢复侧边栏状态
    const savedSidebarState = localStorage.getItem('sidebarCollapsed')
    if (savedSidebarState !== null) {
      sidebarCollapsed.value = savedSidebarState === 'true'
    }
    
    // 恢复主题设置
    const savedTheme = localStorage.getItem('theme') as 'light' | 'dark'
    if (savedTheme) {
      setTheme(savedTheme)
    }
  }
  
  return {
    // 状态
    sidebarCollapsed,
    theme,
    loading,
    breadcrumbs,
    
    // 方法
    toggleSidebar,
    setTheme,
    setLoading,
    setBreadcrumbs,
    initialize
  }
})